// 微信小程序常用API封装

/**
 * 用户授权相关
 */
export const auth = {
  // 获取用户信息（推荐使用）
  getUserProfile(options = {}) {
    return new Promise((resolve, reject) => {
      // 检查是否在微信小程序环境中
      // #ifndef MP-WEIXIN
      reject(new Error('该功能仅在微信小程序中可用'))
      return
      // #endif
      
      uni.getUserProfile({
        desc: options.desc || '用于完善用户资料',
        lang: options.lang || 'zh_CN',
        success: (res) => resolve(res),
        fail: (err) => {
          console.error('getUserProfile失败:', err)
          reject(err)
        }
      })
    })
  },

  // 获取用户手机号
  getPhoneNumber(e) {
    return new Promise((resolve, reject) => {
      // 检查是否在微信小程序环境中
      // #ifndef MP-WEIXIN
      reject(new Error('该功能仅在微信小程序中可用'))
      return
      // #endif
      
      if (e && e.detail && e.detail.errMsg === 'getPhoneNumber:ok') {
        resolve(e.detail)
      } else {
        const errMsg = e && e.detail && e.detail.errMsg ? e.detail.errMsg : '获取手机号失败'
        reject(new Error(errMsg))
      }
    })
  },

  // 检查登录状态
  checkSession() {
    return new Promise((resolve, reject) => {
      // #ifndef MP-WEIXIN
      resolve(false)
      return
      // #endif
      
      uni.checkSession({
        success: () => resolve(true),
        fail: () => resolve(false)
      })
    })
  },

  // 微信登录
  login() {
    return new Promise((resolve, reject) => {
      // #ifndef MP-WEIXIN
      reject(new Error('该功能仅在微信小程序中可用'))
      return
      // #endif
      
      uni.login({
        provider: 'weixin',
        success: (res) => resolve(res),
        fail: (err) => {
          console.error('login失败:', err)
          reject(err)
        }
      })
    })
  },

  // 获取用户信息（需要先调用login获取code，且用户已授权）
  getUserInfo(options = {}) {
    return new Promise((resolve, reject) => {
      // #ifndef MP-WEIXIN
      reject(new Error('该功能仅在微信小程序中可用'))
      return
      // #endif
      
      uni.getUserInfo({
        provider: 'weixin',
        lang: options.lang || 'zh_CN',
        success: (res) => resolve(res),
        fail: (err) => {
          console.error('getUserInfo失败:', err)
          reject(err)
        }
      })
    })
  },

  // 获取用户授权设置
  getSetting() {
    return new Promise((resolve, reject) => {
      // #ifndef MP-WEIXIN
      reject(new Error('该功能仅在微信小程序中可用'))
      return
      // #endif
      
      uni.getSetting({
        success: (res) => resolve(res),
        fail: (err) => {
          console.error('getSetting失败:', err)
          reject(err)
        }
      })
    })
  },

  // 打开授权设置页面
  openSetting() {
    return new Promise((resolve, reject) => {
      // #ifndef MP-WEIXIN
      reject(new Error('该功能仅在微信小程序中可用'))
      return
      // #endif
      
      uni.openSetting({
        success: (res) => resolve(res),
        fail: (err) => {
          console.error('openSetting失败:', err)
          reject(err)
        }
      })
    })
  }
}

/**
 * 存储相关
 */
export const storage = {
  // 设置存储
  set(key, value) {
    try {
      uni.setStorageSync(key, value)
      return true
    } catch (e) {
      console.error('存储失败:', e)
      return false
    }
  },

  // 获取存储
  get(key, defaultValue = null) {
    try {
      const value = uni.getStorageSync(key)
      return value !== '' ? value : defaultValue
    } catch (e) {
      console.error('获取存储失败:', e)
      return defaultValue
    }
  },

  // 删除存储
  remove(key) {
    try {
      uni.removeStorageSync(key)
      return true
    } catch (e) {
      console.error('删除存储失败:', e)
      return false
    }
  },

  // 清空存储
  clear() {
    try {
      uni.clearStorageSync()
      return true
    } catch (e) {
      console.error('清空存储失败:', e)
      return false
    }
  }
}

/**
 * 界面交互相关
 */
export const ui = {
  // 显示Toast
  showToast(title, options = {}) {
    uni.showToast({
      title,
      icon: options.icon || 'none',
      duration: options.duration || 1500,
      ...options
    })
  },

  // 显示Loading
  showLoading(title = '加载中...') {
    uni.showLoading({ title })
  },

  // 隐藏Loading
  hideLoading() {
    uni.hideLoading()
  },

  // 显示模态框
  showModal(title, content, options = {}) {
    return new Promise((resolve) => {
      uni.showModal({
        title,
        content,
        showCancel: options.showCancel !== false,
        confirmText: options.confirmText || '确定',
        cancelText: options.cancelText || '取消',
        ...options,
        success: (res) => {
          resolve(res)
        }
      })
    })
  },

  // 显示操作菜单
  showActionSheet(itemList, options = {}) {
    return new Promise((resolve, reject) => {
      uni.showActionSheet({
        itemList,
        ...options,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 设置导航栏标题
  setNavigationBarTitle(title) {
    uni.setNavigationBarTitle({ title })
  },

  // 显示导航栏加载动画
  showNavigationBarLoading() {
    uni.showNavigationBarLoading()
  },

  // 隐藏导航栏加载动画
  hideNavigationBarLoading() {
    uni.hideNavigationBarLoading()
  }
}

/**
 * 网络请求相关
 */
export const network = {
  // 获取网络状态
  getNetworkType() {
    return new Promise((resolve, reject) => {
      uni.getNetworkType({
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 监听网络状态变化
  onNetworkStatusChange(callback) {
    uni.onNetworkStatusChange(callback)
  },

  // 停止监听网络状态变化
  offNetworkStatusChange(callback) {
    uni.offNetworkStatusChange(callback)
  }
}

/**
 * 设备相关
 */
export const device = {
  // 获取系统信息
  getSystemInfo() {
    return new Promise((resolve, reject) => {
      uni.getSystemInfo({
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 获取设备信息
  getDeviceInfo() {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      uni.getDeviceInfo({
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
      // #endif
      
      // #ifndef MP-WEIXIN
      this.getSystemInfo().then(resolve).catch(reject)
      // #endif
    })
  },

  // 拨打电话
  makePhoneCall(phoneNumber) {
    return new Promise((resolve, reject) => {
      uni.makePhoneCall({
        phoneNumber,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 剪贴板操作
  setClipboardData(data) {
    return new Promise((resolve, reject) => {
      uni.setClipboardData({
        data,
        success: () => resolve(true),
        fail: (err) => reject(err)
      })
    })
  },

  getClipboardData() {
    return new Promise((resolve, reject) => {
      uni.getClipboardData({
        success: (res) => resolve(res.data),
        fail: (err) => reject(err)
      })
    })
  }
}

/**
 * 文件相关
 */
export const file = {
  // 选择图片
  chooseImage(options = {}) {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: options.count || 1,
        sizeType: options.sizeType || ['original', 'compressed'],
        sourceType: options.sourceType || ['album', 'camera'],
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 上传文件
  uploadFile(url, filePath, name, formData = {}) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url,
        filePath,
        name,
        formData,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(JSON.parse(res.data))
          } else {
            reject(new Error(`上传失败: ${res.statusCode}`))
          }
        },
        fail: (err) => reject(err)
      })
    })
  },

  // 下载文件
  downloadFile(url) {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res)
          } else {
            reject(new Error(`下载失败: ${res.statusCode}`))
          }
        },
        fail: (err) => reject(err)
      })
    })
  }
}

/**
 * 位置相关
 */
export const location = {
  // 获取当前位置
  getLocation(options = {}) {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: options.type || 'gcj02',
        altitude: options.altitude || false,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 打开地图选择位置
  chooseLocation() {
    return new Promise((resolve, reject) => {
      uni.chooseLocation({
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  },

  // 打开地图查看位置
  openLocation(latitude, longitude, options = {}) {
    return new Promise((resolve, reject) => {
      uni.openLocation({
        latitude,
        longitude,
        scale: options.scale || 18,
        name: options.name || '',
        address: options.address || '',
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  }
}

/**
 * 支付相关
 */
export const payment = {
  // 微信支付
  requestPayment(orderInfo) {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      uni.requestPayment({
        ...orderInfo,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
      // #endif
      
      // #ifndef MP-WEIXIN
      reject(new Error('当前平台不支持微信支付'))
      // #endif
    })
  }
}

/**
 * 分享相关
 */
export const share = {
  // 显示分享菜单
  showShareMenu(options = {}) {
    // #ifdef MP-WEIXIN
    uni.showShareMenu({
      withShareTicket: options.withShareTicket || false,
      menus: options.menus || ['shareAppMessage', 'shareTimeline'],
      ...options
    })
    // #endif
  },

  // 更新转发属性
  updateShareMenu(options = {}) {
    // #ifdef MP-WEIXIN
    uni.updateShareMenu(options)
    // #endif
  }
}

/**
 * 二维码相关
 */
export const qrcode = {
  // 获取小程序码
  getMiniProgramCode(scene, page, options = {}) {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      uni.request({
        url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit',
        method: 'POST',
        data: {
          scene,
          page,
          ...options
        },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
      // #endif
      
      // #ifndef MP-WEIXIN
      reject(new Error('当前平台不支持生成小程序码'))
      // #endif
    })
  }
}

// 默认导出所有API
export default {
  auth,
  storage,
  ui,
  network,
  device,
  file,
  location,
  payment,
  share,
  qrcode
}